package cn;
//顺序栈
public class SqStack implements IStack{
    private Object[] stackElem;//对象数组
    private int top;//在非空栈中，top始终指向栈顶元素的下一个存储位置，当栈为空时，top值为0
    //栈的构造函数
    public SqStack(int maxSize){
        top=0;
        stackElem=new Object[maxSize];//为栈分配maxSize个存储单元
    }
    @Override
    public void clear() {
       top=0;

    }

    @Override
    public boolean isEmpty() {
        
        return top==0;
    }

    @Override
    public int length() {//求栈的长度
        
        return top;
    }

    @Override
    public Object peek() {//取出栈顶元素
       if(!isEmpty()){//栈非空
           return stackElem[top-1];
       }else
        return null;
    }

    @Override
    public void push(Object x) throws Exception {//入栈
        if(top==stackElem.length){
            throw new Exception("栈满");//抛出异常
        }else
        stackElem[top++]=x;
        
    }

    @Override
    public Object pop() {//出栈
        if(isEmpty()){
            return null;
        }else
        return stackElem[--top];
    }
    public void display(){
        for(int i=top-1;i>=0;i--){
            System.out.println(stackElem[i].toString()+"");//输出
        }
    }
    
}
